package com.shundr.base;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.widget.ImageView;
import cn.jpush.android.api.JPushInterface;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.batsdk.BatSDK;
import com.shundr.common.model.CheckInfo;
import com.shundr.common.util.ActivityHolder;
import com.shundr.common.util.DateUtil;
import com.shundr.common.util.PrefConstants;
import com.shundr.common.util.PrefUtils;
import com.shundr.common.view.DialogWallet;
import com.shundr.common.view.DialogWalletLow;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.http.HttpExecutor;
import com.shundr.frame.service.PushMessageReceiver;
import com.shundr.frame.service.PushMessageReceiver.EventHandler;
import com.shundr.frame.util.LLogger;
import com.shundr.frame.util.StringUtil;
import com.shundr.photoview.ImagePagerActivity;
import com.shundr.user.http.UserRequest;
import com.umeng.analytics.MobclickAgent;

/**
 * 基类
 * BaseActivity
 * 
 * @author larry 2015-4-11 下午2:32:56 
 * @version 1.0.0
 *
 */
public class BaseActivity extends SherlockFragmentActivity implements EventHandler{

	protected Context mContext;
	protected ActionBar mActionBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		initActionBar();
		setOverflowButtonAlways();
		ActivityHolder.getInstance().addActivity(this);
		sendBroadcast(new Intent(PushMessageReceiver.ACTION_CHECK_NETWORK));
	}
	
	private void initActionBar(){
		if(getSupportActionBar() != null){
			mActionBar = getSupportActionBar();
			mActionBar.setHomeButtonEnabled(true);
			mActionBar.setDisplayShowTitleEnabled(true);// 隐藏title
			// 隐藏Home logo
			mActionBar.setDisplayShowHomeEnabled(false);
			mActionBar.setDisplayHomeAsUpEnabled(true);
			// 设置ActionBar的导航模式为标准
			mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		}
	}
	
	private void setOverflowButtonAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKey = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
			menuKey.setAccessible(true);
			menuKey.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 退出应用
	 * exitAPP(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	protected void exitAPP(){
		LLogger.e("mHolder : " + ActivityHolder.getInstance().size());
		ActivityHolder.getInstance().finishAllActivity();
		MobclickAgent.onKillProcess(this);
		System.exit(0);
	}
	
	/**
	 * 退到后台
	 * exitHome(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	protected void exitHome(){
		Intent intent = new Intent(Intent.ACTION_MAIN);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意
        intent.addCategory(Intent.CATEGORY_HOME);
        mContext.startActivity(intent);
	}
	
	/**
	 * 预览图片
	 * startImageReview(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * @param context
	 * @param position
	 * @param list
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	protected void openImageReview(Context context, int position,
			ArrayList<String> list) {
		Intent intent = new Intent(context, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, list);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
		mContext.startActivity(intent);
	}
	
	protected void checkWallet(){
		String time = PrefUtils.getPrefString(mContext, PrefConstants.GET_WALLET_TIME, "");
		if(StringUtil.isNull(time)){
			//获取红包
			if(LContext.isLogin()){
				new UserRequest(mContext, new Handler(){

					@Override
					public void handleMessage(Message msg) {
						super.handleMessage(msg);
						switch (msg.what) {
						case UserRequest.CHECK_IN_SUCCESSED:
							CheckInfo info = (CheckInfo)msg.obj;
							if(info.isReceived()){
								PrefUtils.setPrefString(mContext, PrefConstants.GET_WALLET_TIME, DateUtil.getNowTime_1());
							}else{
								showWallet(info);
								PrefUtils.setPrefString(mContext, PrefConstants.GET_WALLET_TIME, DateUtil.getNowTime_1());
							}
							break;

						default:
							break;
						}
					}
					
				}).checkIn();
			}
		}else{
			if(StringUtil.isEqual(time, DateUtil.getNowTime_1())){
				//今天已经领过红包了,明天再来吧
				PrefUtils.setPrefString(mContext, PrefConstants.GET_WALLET_TIME, DateUtil.getNowTime_1());
			}else{
				//获取红包
				if(LContext.isLogin()){
					new UserRequest(mContext, new Handler(){

						@Override
						public void handleMessage(Message msg) {
							super.handleMessage(msg);
							switch (msg.what) {
							case UserRequest.CHECK_IN_SUCCESSED:
								CheckInfo info = (CheckInfo)msg.obj;
								if(info.isReceived()){
									PrefUtils.setPrefString(mContext, PrefConstants.GET_WALLET_TIME, DateUtil.getNowTime_1());
								}else{
									showWallet(info);
									PrefUtils.setPrefString(mContext, PrefConstants.GET_WALLET_TIME, DateUtil.getNowTime_1());
								}
								break;

							default:
								break;
							}
						}
						
					}).checkIn();
				}
			}
		}
	}
	
	/**
	 * 提示红包
	 * showWallet(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * @param info
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	private void showWallet(CheckInfo info){
		int sdkInt = android.os.Build.VERSION.SDK_INT;
		if(sdkInt < 11){
			DialogWalletLow walletLow = new DialogWalletLow(mContext, info.getPoints(), false);
			walletLow.show();
		}else{
			DialogWallet wallet = new DialogWallet(mContext, info.getPoints(), false);
			wallet.show();
		}
	}
	
	/**
	 * 打开网络设置
	 * startNetSetting(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	public void startNetSetting(){
        Intent intent=null;
        //判断手机系统的版本  即API大于10 就是3.0或以上版本 
        if(android.os.Build.VERSION.SDK_INT>10){
            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
        }else{
            intent = new Intent();
            ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
            intent.setComponent(component);
            intent.setAction("android.intent.action.VIEW");
        }
        startActivity(intent);
	}
	
	/**
	 * 
	 * releaseImageView(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * @param imageView
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	public static void releaseImageView(ImageView imageView) {
		if (imageView == null)
			return;
		Drawable drawable = imageView.getDrawable();
		if (drawable != null && drawable instanceof BitmapDrawable) {
			BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
			Bitmap bitmap = bitmapDrawable.getBitmap();
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onStart() {
		super.onStart();
		BatSDK.doActivityStart(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		LContext.width = dm.widthPixels; // 当前屏幕像素
		LContext.height = dm.heightPixels; // 当前屏幕像素
		JPushInterface.onResume(mContext);
		PushMessageReceiver.mListeners.add(this);
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		JPushInterface.onPause(mContext);
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		BatSDK.doActivityStop(this);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
	}

	@Override
	public void finish() {
		super.finish();
	}

	@Override
	public void onBackPressed() {
		HttpExecutor.cancel(mContext);
		super.onBackPressed();
	}

	@Override
	public void onNetChange() {
		if(LContext.isNetworkConnected){
//			LLogger.e("larry", "网络已连接");
		}else{
//			LLogger.e("larry", "网络已断开");
//			ToastHelper.toastShort(mContext, "网络已断开");
		}
	}
	
	private int screenWidth = LContext.width;
	private int screenHeight = LContext.height - 100;
	
	/**
	 * 可移动的view
	 */
	public OnTouchListener onMoveListener = new OnTouchListener() {
		int lastX, lastY;
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			 switch (event.getAction()) {  
	            case MotionEvent.ACTION_DOWN:  
	                lastX = (int) event.getRawX();  
	                lastY = (int) event.getRawY();  
	                break;  
	            case MotionEvent.ACTION_MOVE:  
	                int dx = (int) event.getRawX() - lastX;  
	                int dy = (int) event.getRawY() - lastY;  

	                int left = v.getLeft() + dx;  
	                int top = v.getTop() + dy;  
	                int right = v.getRight() + dx;  
	                int bottom = v.getBottom() + dy;  

	                if (left < 0) {  
	                    left = 0;  
	                    right = left + v.getWidth();  
	                }  

	                if (right > screenWidth) {  
	                    right = screenWidth;  
	                    left = right - v.getWidth();  
	                }  

	                if (top < 0) {  
	                    top = 0;  
	                    bottom = top + v.getHeight();  
	                }  

	                if (bottom > screenHeight) {  
	                    bottom = screenHeight;  
	                    top = bottom - v.getHeight();  
	                }  

	                v.layout(left, top, right, bottom);  

	                lastX = (int) event.getRawX();  
	                lastY = (int) event.getRawY();  

	                break;  
	            case MotionEvent.ACTION_UP:  
	                break;  
	            }  
			return false;
		}
	};
	
}
